import React from 'react';
import {Form, Row, Col, Button, Divider, Input, Select, message ,Popconfirm ,Icon} from 'antd';
import Grid from '../../components/table/grid';
import {sessionManager} from '../../utils/sessionStorage';
import qs from 'qs';
import {injectIntl} from 'react-intl';
import axios from 'axios';
import ModifyAcc from './modifyAcc';

const FormItem = Form.Item;
const createForm = Form.create;
const Option=Select.Option;

class SubAccount extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            currentRowInfo: {},
            visible: false,
            stack:[],
            params: {},
            refresh: 0,
            canGetApi:true,
        };
        const common = this.props.intl.messages.common;
        this.columns = [
        {
            title: '分账账号',
            dataIndex: 'account',
            key: 'account',
            width: 150,
        },{
            title: '联系人姓名',
            dataIndex: 'chiefName',
            key: 'chiefName',
            width: 150,
        }, 
        {
            title: '商户名称',
            dataIndex: 'companyName',
            key: 'companyName',
            width: 150,
        }, 
        {
            title: '组织机构代码',
            dataIndex: 'companyOrgCode',
            key: 'companyOrgCode',
            width: 200,
        },
        {
            title: '联系人身份证号',
            dataIndex: 'chiefIdn',
            key: 'chiefIdn',
            width: 200,
        },
        {
            title: '地址',
            dataIndex: 'companyAddress',
            key: 'companyAddress',
            width: 350,
        },
        {
            title: '状态',
            key: 'status',
            render: (text, record) => {
                return(text.status==1?'启用':'禁用')
            },
            width: 180,
        },
        {
            title: common.operation,
            key: 'operation',
            fixed: 'right',
            render: (text, record) => {
                return (
                    <span>
                        <Popconfirm title={`确定修改状态吗？`} okText={common.sure}
                                    onConfirm={() => this.openGroup(text, record,'forbid')}
                                    cancelText={common.cancel}>
                            <a>{text.status==0?'启用':'禁用'}</a>
                        </Popconfirm>
                        <Divider type="vertical"/>
                        <Popconfirm title={`${text.chiefName}的密码将重置为：123456`} okText={common.sure}
                                    onConfirm={() => this.openGroup(text, record,'restPas')}
                                    cancelText={common.cancel}>
                            <a>重置密码</a>
                        </Popconfirm>
                        <Divider type="vertical"/>
                        <a onClick={() => this.openGroup(text, record,'modal')}>修改</a>
                        <Divider type="vertical"/>
                        <a onClick={() => this.openGroup(text, record,'pushId')}>下级管理</a>
                    </span>
                )
            },
            width: 250,
        }];
    }

    openGroup = (t, r,moudle) => {
        sessionManager.set('SubAccount',t);
        switch (moudle) {
            case 'forbid':
                this.changeStatus(t)
                break;
            case 'restPas':
                this.restPas(t);
                    break;
            case 'modal':
                this.setState({
                    visible:true,
                    isModal:true
                })
                break;
            case 'pushId':
                this.setState({
                    stack:this.state.stack.concat([t.id])
                },()=>{
                    console.log(this.state.stack);
                    this.freshTable()
                })
                break;    
            default:
                console.log('error')
        }
    }

    changeStatus=(t)=>{
        console.log(t);
        axios.post('/api/corp/globalStatus/update',{status:t.status==1?0:1,id:t.id}).then(res=>{
            if(res){
                this.setState({
                    refresh:this.state.refresh+1
                })
            }
        })
    }

    restPas=(t)=>{
        console.log(t);
        axios.post('/api/corp/globalPawwoerd/reset',{account:t.account}).then(res=>{
            if(res){
                message.success('重置密码成功，密码123456')
            }
        })
    }

    //清空
    handleReset = () => {
        this.props.form.resetFields();
    }
    //表单验证
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                console.log('Errors in form!!!');
                return;
            }
            console.log(values);
            this.setState({
                params: {...values,...{billUserId:this.state.stack[this.state.stack.length-1]}},
                refresh: this.state.refresh + 1
            });
        });
    };

    freshGrid = () => {
        this.setState({
            refresh: this.state.refresh + 1
        });
    };

    handleCancel = () => {
        this.setState({
            visible: false,
            canGetApi:true
        });
    };
    getApi=()=>{
        this.setState({
            canGetApi: false,
        });
    }

    freshTable=()=>{
        this.setState({
            refresh:this.state.refresh+1,
            params:Object.assign(this.state.params,{billUserId:this.state.stack[this.state.stack.length-1]})
        })
    }

    freshStack=()=>{
        this.setState({
            stack: this.state.stack.filter((_, i) => i !== this.state.stack.length-1)
        },()=>{
            this.freshTable();
        })
    }


    render() {
        const {getFieldDecorator} = this.props.form;
        const common = this.props.intl.messages.common;
        const token=JSON.parse(sessionStorage.getItem("token")||{}).token;
        let locale=sessionManager.get('locale');
        let exportQs=`${qs.stringify(this.state.params)}&token=${token}&locale=${locale}`;
        return (
            <div>
                <form form={this.props.form} onSubmit={this.handleSubmit}>
                    <Row gutter={16}>
                        <Col xl={5} xxl={3}>
                            <FormItem
                            >
                                {getFieldDecorator(`companyName`)(
                                    <Input placeholder={'商户名称'}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col xl={5} xxl={3}>
                            <FormItem
                            >
                                {getFieldDecorator(`account`)(
                                    <Input placeholder={'账号'}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col xl={3}>
                        <FormItem>
                            {getFieldDecorator('status')(
                                <Select optionLabelProp="children" optionFilterProp="children" placeholder={'选择用户'} allowClear={true}>
                                    <Option value={'0'} key={0}>禁用</Option>
                                    <Option value={'1'} key={1}>启用</Option>
                                </Select>
                            )}
                        </FormItem>
                        </Col>
                        <Col span={11}>
                            <FormItem>
                               <Button type="primary" className="ant-btn-84" htmlType="submit">{common.search}</Button>
                               <Button type="primary" style={{marginRight:8}} onClick={()=>{this.setState({visible:true,isModal:false})}}>{'添加分账用户'}</Button>
                               <a href={`${axios.defaults.baseURL}/api/corp/globalList/export?${exportQs}`}>
                                    <Button style={{marginRight:8}} type="primary">导出报表</Button>
                               </a>
                               {this.state.stack.length>0&&<Button onClick={this.freshStack}>
                                 <Icon type="rollback"/>上一级
                                </Button>}
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                {/* {this.state.stack.length>0&&<a onClick={this.freshStack} style={{marginBottom:8,display:'block'}}>上一级</a>} */}
                <Grid refresh={this.state.refresh} params={this.state.params}
                      columns={this.columns} url="/api/corp/qry"/>
                <ModifyAcc freshTable={this.freshTable} stack={this.state.stack} getApi={this.getApi} canGetApi={this.state.canGetApi} visible={this.state.visible} title={common.modifyStub} onCancel={this.handleCancel} isModal={this.state.isModal}/>
            </div>
        )
    }
}

//ant 表格验证需要创建表格-createForm
SubAccount = createForm()(SubAccount);
export default injectIntl(SubAccount)

